package com.zjh.securitysplit.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Auther: zhaojh
 * @Date: 2025/9/4 - 09 - 04 - 0:28
 * @Description: com.zjh.securitysplit.filter
 * @version: 1.0
 */

public class LoginFilter extends UsernamePasswordAuthenticationFilter {



    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
        //post判断
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        try {
            Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            String username = map.get(getUsernameParameter()).toString();
            String password = map.get(getPasswordParameter()).toString();
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request, authenticationToken);
            return this.getAuthenticationManager().authenticate(authenticationToken);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }



}
